<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>kilom聊天室</title>
    <script src="./k-coder.js"></script>
</head>

<body>

    <div id="loginDiv" hidden>
        <input id="iptName" placeholder="请输入你的名称"></input>
        <button id="btnLogin">登录</button>
    </div>

    <div id="selectRoomsDiv" hidden>
        <select id="selectRooms">
        </select>
        <button id="btnJoin">加入房间</button>
    </div>

    <div id="roomDiv" hidden>
        <a>当前房间：<a id="curRoom"></a></a>
        <a>在线人数：<a id="online"></a></a>
        <input id="iptChat" placeholder="聊天内容"></input>
        <button id="btnChat">发送</button>
        <button id="btnExit">退出</button>
        <div id="chatDiv">

        </div>

    </div>

    <script>

        let loginDiv = document.getElementById("loginDiv");
        let selectRoomsDiv = document.getElementById("selectRoomsDiv");
        let iptName = document.getElementById("iptName");
        let btnLogin = document.getElementById("btnLogin");
        let selectRooms = document.getElementById("selectRooms");
        let btnJoin = document.getElementById("btnJoin");
        let roomDiv = document.getElementById("roomDiv");
        let curRoom = document.getElementById("curRoom");
        let online = document.getElementById("online");
        let iptChat = document.getElementById("iptChat");
        let btnChat = document.getElementById("btnChat");
        let btnExit = document.getElementById("btnExit");
        let chatDiv = document.getElementById("chatDiv");
        let playerDic = {};

        function showDiv(div) {
            [loginDiv, selectRoomsDiv, roomDiv].forEach(_div => _div.hidden = div != _div);
        }

        let { ObjCoder, BinaryWriter, BinaryReader } = kcoder;
        const w = new BinaryWriter();
        const r = new BinaryReader();

        function encode(msgId, msg) {
            w.start();
            w.uint = msgId;
            return ObjCoder.encode(msg, w).end();
        }

        function decode(data) {
            r.start(data);
            let msgId = r.uint;
            let msg = ObjCoder.decode(r);
            return { msgId, msg };
        }

        const msgId = {
            getConnector: 1,
            join: 2,
            joinRoom: 3,
            chat: 4,
            leave: 5,
        }

        let socket = new WebSocket("ws://localhost:8000");
        function send(msgId, msg) {
            socket.send(encode(msgId, msg));
            console.log("发送：", { msgId, msg });
        }
        socket.binaryType = "arraybuffer";
        socket.onopen = e => {
            send(msgId.getConnector);
        }

        socket.onmessage = e => {
            let data = decode(new Uint8Array(e.data));
            if (data.msgId == msgId.getConnector) {
                socket.close();
                socket = new WebSocket(data.msg.url);

                socket.binaryType = "arraybuffer";
                socket.onopen = () => {
                    showDiv(loginDiv);
                    btnLogin.onclick = e => {
                        if (iptName.value) {
                            send(msgId.join, { name: iptName.value });
                        } else {
                            alert("请输入名称");
                        }
                    }
                }
                socket.onmessage = e => {
                    let data = decode(new Uint8Array(e.data));
                    function showRoomsDiv() {
                        let { err, roomIds } = data.msg;
                        if (err) {
                            alert(err);
                            return;
                        }
                        showDiv(selectRoomsDiv);
                        let html = "";
                        for (let roomId of roomIds) {
                            html += `<option value="${roomId}">房间${roomId}</option>`;
                        }
                        selectRooms.innerHTML = html;
                        btnJoin.onclick = e => {
                            send(msgId.joinRoom, { roomId: Number(selectRooms.value) });
                        }
                    }

                    console.log("接收：", data);

                    switch (data.msgId) {
                        case msgId.join:
                        case msgId.leave:
                            showRoomsDiv();
                            break;
                        case msgId.joinRoom:
                            let { roomId, players, chats, err } = data.msg;
                            if (data.msg.err) {
                                alert(data.msg.err);
                                break;
                            }
                            showDiv(roomDiv);
                            curRoom.innerHTML = roomId + "";
                            online.innerHTML = players.length + "";
                            playerDic = {};
                            for (let player of players) {
                                playerDic[player.uid] = player;
                            }
                            let chatHtml = "";
                            for (let chat of chats) {
                                chatHtml += `<p>${chat}</p>`
                            }
                            chatDiv.innerHTML = chatHtml;
                            btnChat.onclick = e => {
                                if (iptChat.value) {
                                    send(msgId.chat, { chat: iptChat.value });
                                }
                            }
                            btnExit.onclick = e => {
                                send(msgId.leave);
                            }
                            break;
                        case msgId.chat:
                            let { chat, onlineCount } = data.msg;
                            chatDiv.innerHTML += `<p>${chat}</p>`;
                            if (onlineCount != undefined) {
                                online.innerHTML = onlineCount + "";
                            }
                            break;
                    }
                }
            }
        }

    </script>


</body>

</html>